package net.newsmth.smthapp.android.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import net.newsmth.smthapp.android.config.AppSettings;
import net.newsmth.smthapp.android.config.AppSettingsImpl;
import net.newsmth.smthapp.android.config.SmthConnection;
import net.newsmth.smthapp.android.config.SmthNetStatusType;
import net.newsmth.smthapp.android.util.TextCreatorUtil;
import net.newsmth.smthapp.android.widget.ErrorView;

/**
 * Created by Hatsune Miku on 3/25/14.
 */
public abstract class BaseActivity extends Activity  {
    protected AppSettings appSettings = AppSettingsImpl.getCurrent();
    protected SmthConnection connection = SmthConnection.getCurrent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerNetworkHandler();
    }

    protected void restartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    public void registerNetworkHandler() {
        connection.setHandler(getNetworkHandler());
    }

    public Handler getNetworkHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == SmthConnection.SMTH_NETWORK_HANDLER) {
                    Bundle data = msg.getData();
                    SmthNetStatusType statusType = SmthNetStatusType.valueOf(data.getString(
                            SmthConnection.SMTH_NETWORK_STATUS_TYPE_KEY));
                    String errorMessage = data.getString(SmthConnection.SMTH_NETWORK_Error_DESCRIPTION_KEY);

                    ErrorView errorView = getGeneralErrorView();

                    if (errorView != null) {
                        switch (statusType) {
                            case OK:
                                errorView.hideGeneralErrorMessage();
                                break;
                            case TOKEN_FAILURE:
                                errorView.redirectToLogin();
                            default:
                                errorView.showGeneralErrorMessage(
                                        TextCreatorUtil.getNetworkMessage(
                                                appSettings.getAppContext(),
                                                statusType, errorMessage));
                        }
                    }
                }
            }
        };
    }

    protected abstract ErrorView getGeneralErrorView();
}
